package Bean;

import Action.Sys.Setting;
import com.sun.istack.NotNull;
import org.apache.struts2.ServletActionContext;
import org.hibernate.Session;
import tools.HibernateTools;

import javax.persistence.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Blob;
import java.util.*;

@Entity
@Table(name = "bookinfo", schema = "bookloansystem", catalog = "")
public class BookInfoEntity {

    int id;
    String book_name;
    String book_Author;
    String book_Info;
    String book_tag1;
    String book_tag2;
    String book_tags;
    Blob  book_picture;
    int  vister;
    int sum;
    int used;

    int comment_size=0;

    List<BookCommentEntity> bookCommentEntitys;
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    @NotNull
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
    @Basic
    @Column(name = "name")
    @NotNull
    public String getBook_name() {
        return book_name;
    }

    public void setBook_name(String book_name) {
        this.book_name = book_name;
    }
    @Basic
    @Column(name = "author")
    @NotNull
    public String getBook_Author() {
        return book_Author;
    }
    public String SummaryBook_Author() {
        if (book_Author.length()>6){
            return book_Author.substring(0, 6)+"...";
        }
        return book_Author;
    }

    public void setBook_Author(String book_Author) {
        this.book_Author = book_Author;
    }
    @Basic
    @Column(name = "info")
    @NotNull
    public String getBook_Info() {
        return book_Info;
    }

    public String SummaryBook_Info() {
        String middle=book_Info.replace(" ", "");//去掉空格
        if (middle.length()>12){
            return middle.substring(0, 12)+"....";
        }
        return middle;
    }

    public void setBook_Info(String book_Info) {
        this.book_Info = book_Info;
    }
    @Basic
    @Column(name = "tag1")
    public String getBook_tag1() {
        return book_tag1;
    }
    public void setBook_tag1(String book_tag1) {
        this.book_tag1 = book_tag1;
    }
    @Basic
    @Column(name = "tag2")
    public String getBook_tag2() {
        return book_tag2;
    }

    public void setBook_tag2(String book_tag2) {
        this.book_tag2 = book_tag2;
    }
    @Basic
    @Column(name = "tags")
    public String getBook_tags() {
        return book_tags;
    }

    public void setBook_tags(String book_tags) {
        this.book_tags = book_tags;
    }
    @Basic
    @Column(name = "book_picture")
    public Blob getBook_picture() {
        return book_picture;
    }

    public void setBook_picture(Blob book_picture) {
        this.book_picture = book_picture;
    }
    @Basic
    @Column(name = "vister")
    public int getVister() {
        return vister;
    }

    public void setVister(int vister) {
        this.vister = vister;
    }
    @Basic
    @Column(name = "sum")
    public int getSum() {
        return sum;
    }

    public void setSum(int sum) {
        this.sum = sum;
    }
    @Basic
    @Column(name = "used")
    public int getUsed() {
        return used;
    }

    public void setUsed(int used) {
        this.used = used;
    }
    @Basic
    @Column(name = "cache_comment_size")
    public int getComment_size() {
        return comment_size;
    }

    public void setComment_size(int comment_size) {
        this.comment_size = comment_size;
    }

    //增强方法--获取评论
    @Transient
    public List<BookCommentEntity> getBookCommentEntitys() {
        Session session = HibernateTools.getSession();
        bookCommentEntitys=session.createQuery("from BookCommentEntity where bookId=?").setParameter(0,id).getResultList();
        comment_size=bookCommentEntitys.size();//被动更新评论量
        session.update(this);
        HibernateTools.commit(session);
        return bookCommentEntitys;
    }


    //浅层挖掘相关书籍
    public LinkedList<BookInfoEntity> related_books(int size){//会有重复书籍重复书籍用于加分
        LinkedList<Object[]> data=new LinkedList<>();
        Session session = HibernateTools.getSession();
//        String hql="from BookInfoEntity where book_tag1 = '"+this.book_tag1+"' and id != "+id+" order by (used*50+vister) desc";//浏览最多
        String hql="from BookInfoEntity where book_tag1 = '"+this.book_tag1+"' and id != "+id;
//        session.createQuery("from BookInfoEntity where book_tag1=1 order by (used*10+vister)");
        HashSet<String> hashSet=new HashSet<>();
        for (String s : this.getBook_name().split("")) {
            hashSet.add(s);
        }
        List resultList = session.createQuery(hql).getResultList();
        for (Object o : resultList) {
            BookInfoEntity bookInfoEntity=(BookInfoEntity)o;
            Integer num=bookInfoEntity.getUsed()*50+bookInfoEntity.getVister();
            for (String s : bookInfoEntity.getBook_name().split("")) {
                if (hashSet.contains(s)){
                    num*=10;
                }
            }
            data.addLast(new Object[]{bookInfoEntity,num});
        }
        Collections.sort(data, new Comparator<Object[]>() {
            @Override
            public int compare(Object[] o1, Object[] o2) {
                return ((Integer) o2[1])-(Integer) o1[1];
            }
        });

        LinkedList<BookInfoEntity> res=new LinkedList<>();
        for (Object[] datum : data) {
            if (res.size()<size+1){
                res.addLast((BookInfoEntity) datum[0]);
            }
        }

        return res;
    }



    /**
     * 图书图片生成器--建议对象获取使用load而不是get
     * @param refresh 强制刷新--用于图书管理时,刷新的及时性
     * @return
     */
    public boolean build_image(boolean refresh)
    {
        try {
            File dir = new File(ServletActionContext.getServletContext().getRealPath("cache") +"/booksInfo/");
            if (!dir.exists()) {// 判断目录是否存在
                if (dir.mkdirs()) {
                    System.out.println("图片缓冲区建立成功");
                }
                else System.err.println("图片缓存区无效!!!!!!!!");
            }

            Blob blob=this.getBook_picture();
            InputStream inputStream= blob.getBinaryStream();
            if (!refresh) {//强制刷新
                //数据加载模式3
                if (Setting.SYS_cache_Model == 2) {
                    File file = new File(ServletActionContext.getServletContext().getRealPath("cache") + "/booksInfo/" + this.getBook_name() + ".jpg");
                    if (file.exists() && (System.currentTimeMillis() - file.lastModified()) <= Setting.SYS_min_cache_time * 60 * 1000) {
                        return true;
                    }
                }//数据加载模式2
                else if (Setting.SYS_cache_Model == 3) {
                    File file = new File(ServletActionContext.getServletContext().getRealPath("cache") + "/booksInfo/" + this.getBook_name() + ".jpg");
                    if (file.exists()) {

                        return true;
                    }
                }
            }else {
                System.out.println("强制刷新图书缓存");
            }
            //数据加载模式1   或者本地文件没有命中
            FileOutputStream file = new FileOutputStream( ServletActionContext.getServletContext().getRealPath("cache") +"/booksInfo/"+ this.getBook_name() + ".jpg");
            int len = (int) blob.length();
            byte[] buffer = new byte[len]; // 建立缓冲区
            while ((len = inputStream.read(buffer)) != -1) {
                file.write(buffer, 0, len);
            }
            file.close();
            inputStream.close();
        }catch (Exception e){
            System.out.println("图片缓冲异常");
//            e.fillInStackTrace();
            return false;
        }

        return true;
    }

    //图书热度计算

    public int hot_index(){
        return comment_size*3+vister;//短期借阅量影响系统性能
    }

}
